import React, { useState, useEffect, useRef } from 'react';
import {
    Card,
    Button,
    Form,
    Input,
    Select,
    DatePicker,
    Checkbox,
    Icon,
    Col,
    TreeSelect,
    message,
    InputNumber,
    Modal
} from 'antd';
import { history } from 'umi'
import { FormContainer } from '@/components/UserForm';
import BraftEditor from 'braft-editor';
import { get as getPath } from 'object-path';
import { customUpload } from '@/utils/fileUpload';
import moment from 'moment/moment';
import FileUpload from '@/components/Custom/FileUpload';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import pageTabUtil from '@/utils/pageTabUtil';
import { debounce } from 'lodash';
import { ChildTask, TipBox, RelativeLink, TaskListItem } from '../../components';
import { showTipBoxInfoModal } from '../containers/MyTaskInfoModal';
import {
    getEmployeeList,
    launchTask,
    frontTask,
    relateTaskList,
    addChangeTask,
    createSubTask,
    restartTask,
    copyTask,
    searchParentTask,
    changeParentTaskCheck
} from '../../services';
import { TimeFormatForm, TaskStatus } from '../../utils';

import styles from './AddTask.less';

const { Option } = Select;

const { confirm } = Modal;

const getLocalItem = key => {
    if (key) {
        const nowItem = localStorage.getItem(key);
        if (nowItem) {
            return JSON.parse(nowItem);
        }
    }
    return null;
};
const AddTask = ({ location, form }) => {
    const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};
    const { getFieldDecorator } = form;
    // 发起任务modal跳转携带的参数
    const { query } = location;
    const formLayout = {
        wrapperCol: { span: 18 },
        labelCol: { span: 6 }
    };
    const getTitle = () => {
        if (getPath(query, 'type')) {
            switch (getPath(query, 'type')) {
                case 'new_child_task':
                    return '新增子任务';
                case 'change_task':
                    return '变更任务';
                case 'copy_task':
                    return '复制任务';
                case 'restart_task':
                    return '重新发起';
                default:
                    return '发起任务';
            }
        } else {
            return '发起任务';
        }
    };
    const isFirstRun = useRef(true);
    const [isCheck, setIsCheck] = useState(false);
    const [loading, setLoading] = useState(false);
    const localItem = getLocalItem(getPath(query, 'key', ''));
    const [initInfo, seInitInfo] = useState(localItem ? localItem.taskParam : {});
    const [parentTaskList, setParentTaskList] = React.useState([]);
    // console.log(initInfo, '=============================');
    const [parentRec, setParentRec] = useState(localItem ? localItem.record : {});
    const [disabled, setDisabled] = useState(false);
    const [startMode, setStartMode] = useState(
        getPath(initInfo, 'planStartTime') && getPath(initInfo, 'planStartTime').indexOf('00:00:00') === -1
            ? 'time'
            : 'date'
    );
    const [endMode, setEndMode] = useState(
        getPath(initInfo, 'planEndTime') && getPath(initInfo, 'planEndTime').indexOf('23:59:59') === -1
            ? 'time'
            : 'date'
    );
    const [startDate, setStartDate] = useState('');
    const [endDate, setEndDate] = useState('');
    const [workTime, setWorkTime] = useState('小时 (0天0小时0分钟)');
    const [employeeList, setEmployeeList] = useState([]);
    const [fileList, setFileList] = useState([]);
    const [uploadResource, setUploadResource] = useState(null);
    const [advanceAlert, setAdvanceAlert] = useState(1);
    const [workDays, setWorkdays] = useState([]);
    // 关联链接列表
    // const [urlList, setUrlList] = useState([]);
    const [priorityList, setPriorityList] = useState([]);
    const [childList, setChildList] = useState(getPath(initInfo, 'subtaskList', []));
    const [frontList, setFrontList] = useState([]);
    const [relateTask, setRelateTask] = useState([]);

    // 是否周期任务联动-每周每月每天-具体日期
    const [showDays, setShowDays] = useState(false);
    const [cycleTaskCanPass, setCycleTaskCanPass] = useState(true);

    // const plainOptions = ['IM消息', '系统提醒', '邮箱', '短信'];
    const controls = [
        'undo',
        'redo',
        'separator',
        'font-size',
        'line-height',
        'letter-spacing',
        'separator',
        'text-color',
        'bold',
        'italic',
        'underline',
        'strike-through',
        'separator',
        'superscript',
        'subscript',
        'remove-styles',
        'emoji',
        'separator',
        'text-indent',
        'text-align',
        'separator',
        'headings',
        'list-ul',
        'list-ol',
        'blockquote',
        'code',
        'separator',
        'media',
        'link',
        'hr',
        'separator',
        'clear'
    ];
    const getEmployeeName = (val, list = []) => {
        const arr = list.filter(item => item.value === val);
        if (arr && arr.length > 0) {
            return arr[0].employeeName || '';
        }
        return '';
    };
    const handleTime = (value, type) => {
        if (type === 'start') {
            setStartDate(value.format(startMode === 'date' ? 'YYYY-MM-DD 00:00:00' : 'YYYY-MM-DD HH:mm:ss'));
        } else {
            setEndDate(value.format(endMode === 'date' ? 'YYYY-MM-DD 23:59:59' : 'YYYY-MM-DD HH:mm:ss'));
        }
    };
    const handleTimePanel = (value, mode, type) => {
        if (type === 'start') {
            setStartMode(mode);
        } else {
            setEndMode(mode);
            setEndDate(value.format(mode === 'date' ? 'YYYY-MM-DD 23:59:59' : 'YYYY-MM-DD HH:mm:ss'));
        }
    };

    const handleTimeChange = (date, dateString, type) => {
        setCycleTaskCanPass(true);
        if (!dateString) {
            if (type === 'start') {
                setStartDate('');
            } else {
                setEndDate('');
            }
        } else {
            handleTime(date, type);
        }
    };
    const submitTip = values => {
        const { auditEmployeeCode } = values;
        if (auditEmployeeCode) {
            const auditEmployeeName = getEmployeeName(auditEmployeeCode, employeeList);
            confirm({
                title: '提示',
                content: (
                    <>
                        <TipBox
                            title="提交成功！"
                            content={
                                <>
                                    <div style={{ textAlign: 'center' }}>
                                        需待审核人【{auditEmployeeName || ''}】审核通过后
                                    </div>
                                    <div style={{ textAlign: 'center' }}>系统方可指派给执行人</div>
                                </>
                            }
                        />
                        <TipBox content="请至“我发起的”列表查看已发起的任务" />
                    </>
                ),
                className: styles.confirmModal
            });
        } else {
            showTipBoxInfoModal({
                title: '提示',
                rows: ['提交成功！', '请至“我发起的”列表查看已发起的任务！']
            });
        }
    };

    const handleSubmit = async () => {
        setIsCheck(true);
        form.validateFields(async (err, values) => {
            if (values.cycleTaskFlag) {
                const { cycleTaskType = '', cycleTaskDayList = [], planStartTime = '', planEndTime = '' } = values;
                if (cycleTaskType && cycleTaskDayList.length > 0 && planEndTime) {
                    const dateList = [];
                    const tempStartTime = planStartTime || moment();
                    for (
                        let i = moment(tempStartTime.format('YYYY-MM-DD 00:00:00')).unix();
                        i < moment(planEndTime.format('YYYY-MM-DD 23:59:59')).unix();
                        i += 24 * 60 * 60
                    ) {
                        const nowMoment = moment(i * 1000);
                        dateList.push({
                            day: nowMoment.day() || 7,
                            date: nowMoment.date()
                        });
                    }
                    let tempArr = [];
                    if (cycleTaskType === 1) {
                        if (cycleTaskDayList.includes(1)) {
                            tempArr = [1, 2, 3, 4, 5];
                        }
                        if (cycleTaskDayList.includes(2)) {
                            tempArr.push(6);
                        }
                        if (cycleTaskDayList.includes(3)) {
                            tempArr.push(7);
                        }
                    } else {
                        tempArr = cycleTaskDayList;
                    }
                    let flag = false;
                    dateList.forEach(item => {
                        if (cycleTaskType === 1 || cycleTaskType === 2) {
                            if (tempArr.includes(item.day)) {
                                flag = true;
                            }
                        } else if (cycleTaskType === 3) {
                            if (tempArr.includes(item.date)) {
                                flag = true;
                            }
                        }
                    });
                    if (flag) {
                        setCycleTaskCanPass(true);
                    } else {
                        setCycleTaskCanPass(false);
                        return;
                    }
                }
            }
            if (!err) {
                if (
                    (values.personalPrivacyFlag === 1 &&
                        (!values.participantEmployeeCodeList ||
                            (values.participantEmployeeCodeList && values.participantEmployeeCodeList.length === 0)) &&
                        !values.auditEmployeeCode &&
                        !values.acceptanceEmployeeCode) ||
                    values.personalPrivacyFlag === 0 ||
                    values.cycleTaskFlag === 1
                ) {
                    setLoading(true);
                    const { taskDesc, auditEmployeeCode, personalPrivacyFlag } = values;
                    if (childList) {
                        const arrTemp = childList.filter(
                            item => item.taskName && item.executeEmployeeCode && item.planEndTime && item.taskPriority
                        );
                        if (arrTemp.length < childList.length) {
                            message.error('必填参数未填');
                            setLoading(false);
                            return;
                        }
                        if (auditEmployeeCode) {
                            const arrTemp2 = childList.filter(item => item.auditEmployeeCode);
                            if (arrTemp2.length < childList.length) {
                                message.error('当前任务已选审核人，批量新增的子任务也需选择审核人');
                                setLoading(false);
                                return;
                            }
                        }
                        if (personalPrivacyFlag === 1) {
                            const arrTemp3 = childList.filter(
                                item =>
                                    item.auditEmployeeCode ||
                                    item.acceptanceEmployeeCode ||
                                    (item.participantEmployeeCodeList && item.participantEmployeeCodeList.length > 0)
                            );
                            if (arrTemp3.length > 0) {
                                message.error('该任务为隐私任务，不可填写审核人、验收人或参与人');
                                setLoading(false);
                                return;
                            }
                        }
                    }

                    if (values.taskDesc && values.taskDesc.toHTML().length > 20000) {
                        message.error('任务描述内容过多');
                        setLoading(false);
                        return;
                    }
                    // if (
                    //     getPath(initInfo, 'parentPlanEndTime', '') &&
                    //     moment(endDate).isAfter(getPath(initInfo, 'parentPlanEndTime'))
                    // ) {
                    //     const str = moment(getPath(initInfo, 'parentPlanEndTime')).format(
                    //         getPath(initInfo, 'parentPlanEndTime').indexOf('23:59:59') !== -1
                    //             ? 'YYYY-MM-DD'
                    //             : 'YYYY-MM-DD HH:mm'
                    //     );
                    //     message.error(`不可大于上级任务截止时间${str}`);
                    //     setLoading(false);
                    //     return;
                    // }
                    // if (endDate && childList.length > 0) {
                    //     let tempFlag = false;
                    //     childList.forEach(item => {
                    //         if (moment(item.planEndTime).isAfter(endDate)) {
                    //             tempFlag = true;
                    //         }
                    //     });
                    //     if (tempFlag) {
                    //         const str = moment(endDate).format(endMode === 'date' ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm');
                    //         message.error(`不可大于上级任务截止时间${str}`);
                    //         setLoading(false);
                    //         return;
                    //     }
                    // }
                    const newLinkList =
                        values.relateLinkList &&
                        values.relateLinkList.filter(item => item.link && item.link.length > 0).map(item => item.link);

                    // const addNoticeList = values.noticeWayList
                    //     ? [...new Set(values.noticeWayList.concat(['IM消息', '系统消息']))]
                    //     : ['IM消息', '系统消息'];
                    // const newNoticeList = addNoticeList.map(item => getNoticeWayList(item));

                    const params = {
                        ...values,
                        id: getPath(initInfo, 'id', ''),
                        planStartTime:
                            startDate ||
                            (values.planStartTime &&
                                values.planStartTime.format(
                                    startMode === 'date' ? 'YYYY-MM-DD 00:00:00' : 'YYYY-MM-DD HH:mm:ss'
                                )) ||
                            '',
                        planEndTime:
                            endDate ||
                            (values.planEndTime &&
                                values.planEndTime.format(
                                    endMode === 'date' ? 'YYYY-MM-DD 23:59:59' : 'YYYY-MM-DD HH:mm:ss'
                                )) ||
                            '',
                        taskDesc: taskDesc && taskDesc.toHTML(),
                        subtaskList: childList,
                        relateLinkList: newLinkList,
                        noticeWayList: values.noticeWayList,
                        estimateWorkDuration: values.estimateWorkDuration && values.estimateWorkDuration * 60,
                        resourceRelation: uploadResource ? [uploadResource] : [],
                        remindDate: values.remindDate && values.remindDate.format('YYYY-MM-DD HH:mm:00'),
                        enableChildrenQueryFlag: values.enableChildrenQueryFlag ? 1 : 0
                    };
                    let result = {};

                    if (getPath(query, 'type') === 'new_child_task') {
                        params.parentTaskId = getPath(parentRec, 'id', undefined);
                        result = await createSubTask(params);
                    } else if (getPath(query, 'type') === 'change_task') {
                        if (values.parentTaskId) {
                            const filterList = parentTaskList.filter(item => item.taskId === values.parentTaskId);
                            params.parentTaskId = values.parentTaskId;
                            params.parentTaskName = filterList && filterList.length > 0 ? filterList[0].taskName : '';
                            // const tempTime = filterList && filterList.length > 0 ? filterList[0].planEndTime : '';
                            // if (tempTime && moment(endDate).isAfter(tempTime)) {
                            //     const str = moment(tempTime).format(
                            //         tempTime.indexOf('23:59:59') !== -1 ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm'
                            //     );
                            //     message.error(`当前截止时间不可大于上一级任务截止时间${str}`);
                            //     setLoading(false);
                            //     return;
                            // }
                        }
                        if (initInfo && initInfo.parentTaskId) {
                            const res = await changeParentTaskCheck(params);
                            const { code, data } = res;
                            if (code === 10000) {
                                if (data) {
                                    const { taskStatus, inAuditFlag, operateName, inAcceptanceFlag } = data;
                                    let nowStatus = '';
                                    if (taskStatus === TaskStatus.CANCEL) {
                                        nowStatus = '已取消';
                                    } else if (taskStatus === TaskStatus.FINISH) {
                                        nowStatus = '已完成';
                                    } else if (inAuditFlag) {
                                        nowStatus = `${operateName}待审核`;
                                    } else if (inAcceptanceFlag) {
                                        nowStatus = '待验收';
                                    }
                                    if (nowStatus) {
                                        message.error(`所选的上一级任务已更新状态为${nowStatus}，不允许提交！`);
                                        setLoading(false);
                                        return;
                                    }
                                }
                            }
                        }
                        result = await addChangeTask(params);
                    } else if (getPath(query, 'type') === 'restart_task') {
                        result = await restartTask(params);
                    } else if (getPath(query, 'type') === 'copy_task') {
                        result = await copyTask(params);
                    } else {
                        result = await launchTask(params);
                    }

                    if (result.code === 10000) {
                        if (getPath(query, 'type') !== 'change_task') {
                            // 提交时候的提示弹窗
                            submitTip(values);
                        }
                        pageTabUtil.closeTab();
                    } else {
                        message.error(result.msg);
                    }
                    setLoading(false);
                } else {
                    message.error('该任务为隐私任务，不可填写审核人、验收人或参与人');
                }
            }
        });
    };
    const handleCancel = () => {
        pageTabUtil.closeTab();
    };
    const extraButtons = (
        <span>
            <Button style={{ marginRight: 16 }} onClick={handleCancel}>
                取消
            </Button>
            <Button type="primary" style={{ marginRight: 16 }} onClick={handleSubmit} loading={loading}>
                提交
            </Button>
        </span>
    );

    const handleChildListChange = list => {
        setChildList(list);
    };

    // 提前提醒-固定时间-时长选择
    const getRemindDuration = () =>
        getFieldDecorator('remindDuration', {
            initialValue: getPath(initInfo, 'remindDuration', 10)
        })(
            <Select
                placeholder="请选择提醒时间"
                style={{ marginLeft: 8 }}
                disabled={getPath(query, 'type') === 'change_task'}
            >
                {[1, 5, 10, 15, 20, 25, 30].map(item => (
                    <Option key={item} value={item}>
                        {item}
                    </Option>
                ))}
            </Select>
        );
    // 提前提醒-固定时间-时长选择单位
    const getRemindDurationUnit = () =>
        getFieldDecorator('remindDurationUnit', {
            initialValue: getPath(initInfo, 'remindDurationUnit', 1)
        })(
            <Select
                placeholder="请选择提醒周期"
                style={{ marginLeft: 8 }}
                disabled={getPath(query, 'type') === 'change_task'}
            >
                {[
                    { key: 1, value: '分钟' },
                    { key: 2, value: '小时' },
                    { key: 3, value: '天' }
                ].map(item => (
                    <Option key={item.key} value={item.key}>
                        {item.value}
                    </Option>
                ))}
            </Select>
        );

    const getRemindDate = () =>
        getFieldDecorator('remindDate', {
            rules: [
                {
                    required: true,
                    message: '请选择指定的时间'
                }
            ],
            initialValue: getPath(initInfo, 'remindDate') ? moment(getPath(initInfo, 'remindDate')) : null
        })(
            <DatePicker
                showTime
                placeholder="请选择指定的时间"
                allowClear
                format="YYYY-MM-DD HH:mm"
                style={{ marginLeft: 8 }}
            />
        );

    const handleFileUpload = (showFileListReturn, uploadResourceReturn) => {
        setFileList(showFileListReturn);
        setUploadResource(uploadResourceReturn);
        if (showFileListReturn.length < 5) {
            setDisabled(false);
        } else {
            setDisabled(true);
        }
    };
    const cycleTaskRule = () => (showDays ? [{ required: true, message: ' ' }] : []);
    const cycleTaskTypeForm = (
        <Form.Item className={styles.noTips} style={{ width: 88, marginLeft: 8, marginBottom: 0 }}>
            {getFieldDecorator('cycleTaskType', {
                rules: cycleTaskRule(),
                initialValue: getPath(initInfo, 'cycleTaskType', undefined)
            })(
                <Select
                    placeholder="请选择"
                    disabled={getPath(query, 'type') === 'change_task' || getPath(query, 'type') === 'restart_task'}
                >
                    {[
                        { title: '每天', value: 1 },
                        { title: '每周', value: 2 },
                        { title: '每月', value: 3 }
                    ].map(item => (
                        <Option key={item.value} value={item.value}>
                            {item.title}
                        </Option>
                    ))}
                </Select>
            )}
        </Form.Item>
    );

    const cycleTaskDayList = (
        <Form.Item className={styles.noTips} style={{ flex: 1, marginLeft: 8, marginBottom: 0 }}>
            {getFieldDecorator('cycleTaskDayList', {
                rules: cycleTaskRule(),
                initialValue: getPath(initInfo, 'cycleTaskDayList', [])
            })(
                <Select
                    placeholder="请选择"
                    mode="multiple"
                    allowClear
                    maxTagCount={1}
                    disabled={getPath(query, 'type') === 'change_task' || getPath(query, 'type') === 'restart_task'}
                >
                    {workDays.map(item => (
                        <Option key={item.value} value={item.value}>
                            {item.title}
                        </Option>
                    ))}
                </Select>
            )}
        </Form.Item>
    );
    // 不允许添加尺寸大于100M的文件
    const myValidateFn = file => {
        if (file.size > 1024 * 1024 * 10) {
            message.error('图片不能大于10M！');
            return false;
        }
        return true;
    };
    // 任务描述报错提示
    const handleEditorChange = editorState => {
        const html = editorState.toHTML();
        if (html.length > 20000) {
            message.error('任务描述内容过多');
        }
    };
    const myUploadFn = param => {
        const onSuccess = (response, file) =>
            param.success({
                url: response.data[0].url,
                meta: {
                    id: file.name,
                    title: file.name,
                    alt: file.name
                }
            });
        customUpload({ files: param, onSuccess });
    };
    // 获取上一级任务列表
    const getParentTaskList = async (val = '') => {
        const res = await searchParentTask({
            parentTaskId: val.trim() ? undefined : getPath(initInfo, 'parentTaskId', '') || undefined,
            taskId: getPath(initInfo, 'id', undefined) || undefined,
            name: val || ''
        });
        if (res && res.code === 10000) {
            const { data } = res;
            setParentTaskList(data);
        }
    };
    // 上一级任务列表搜索
    const handleSearchParent = debounce(value => {
        getParentTaskList(value.trim());
    }, 200);

    const handleChangeParent = debounce(value => {
        if (value === undefined) {
            getParentTaskList();
        }
    }, 200);
    // 获取员工列表
    const fetchEmployeeList = async () => {
        const { companyId } = user;
        const result = await getEmployeeList(companyId);

        if (result.code === 10000) {
            const { data } = result;
            const newData = data.map(item => ({
                ...item,
                value: item.employeeCode,
                title: item.employeeName
            }));
            setEmployeeList(newData);
        } else {
            message.error(result.msg);
        }
    };
    // 前置任务列表
    const fetchFrontList = async value => {
        const params = {
            taskId: getPath(initInfo, 'frontTaskId', ''),
            taskName: value || ''
        };
        const result = await frontTask(params);

        if (result.code === 10000) {
            setFrontList(result.data);
        } else {
            message.error(result.msg);
        }
    };
    // 关联任务列表
    const fetchRelateTask = async value => {
        const params = { taskId: getPath(initInfo, 'relateTaskId', ''), taskName: value || '' };
        const result = await relateTaskList(params);

        if (result.code === 10000) {
            setRelateTask(result.data);
        } else {
            message.error(result.msg);
        }
    };

    // 关联任务列表搜索
    const handleSearch = debounce(value => {
        fetchRelateTask(value);
    }, 200);
    const handleChangeRelate = debounce(value => {
        if (value === undefined) {
            fetchRelateTask();
        }
    }, 200);
    // 前置任务列表搜索
    const handleSearchFront = debounce(value => {
        fetchFrontList(value);
    }, 200);
    // const handleSearchFront = value => {
    //     fetchFrontList(value);
    // };
    const handleChangeFront = debounce(value => {
        if (value === undefined) {
            fetchFrontList();
        }
    }, 200);
    // const handleChangeFront = value => {
    //     if (value === undefined) {
    //         fetchFrontList();
    //     }
    // };

    // 子任务的Col
    const showChildList = () => {
        if (getPath(query, 'type') === 'change_task' || getPath(query, 'type') === 'restart_task' || showDays) {
            return null;
        }
        return (
            <Col vvspan={24} offset={3} style={{ paddingBottom: '30px' }}>
                <ChildTask
                    hasMore
                    parentEndTime={endDate || (initInfo ? initInfo.parentPlanEndTime : undefined)}
                    taskList={childList}
                    employeeList={employeeList}
                    isCheck={isCheck}
                    setIsCheck={setIsCheck}
                    onChange={handleChildListChange}
                />
            </Col>
        );
    };

    // 计算每日工作时长
    useEffect(() => {
        // 第一次不运行;
        if (isFirstRun.current) {
            isFirstRun.current = false;
            return;
        }

        const time = form.getFieldValue('estimateWorkDuration');
        const newTime = time * 60;
        setWorkTime(TimeFormatForm(newTime));
    }, [JSON.stringify(form.getFieldValue('estimateWorkDuration'))]);

    useEffect(() => {
        setAdvanceAlert(form.getFieldValue('remindType'));
    }, [JSON.stringify(form.getFieldValue('remindType'))]);

    // 是否周期任务联动
    useEffect(() => {
        setCycleTaskCanPass(true);
        if (form.getFieldValue('cycleTaskFlag')) {
            setShowDays(true);
            setChildList([]);
        } else {
            setShowDays(false);
        }
    }, [JSON.stringify(form.getFieldValue('cycleTaskFlag'))]);

    const refreshWorkDays = (type, flag) => {
        setWorkdays([]);
        form.setFieldsValue({
            cycleTaskDayList: flag ? getPath(initInfo, 'cycleTaskDayList', []) : []
        });
        if (type === 1) {
            setWorkdays([
                { title: '工作日', value: 1 },
                { title: '周六', value: 2 },
                { title: '周日', value: 3 }
            ]);
        } else if (type === 2) {
            setWorkdays([
                { title: '周一', value: 1 },
                { title: '周二', value: 2 },
                { title: '周三', value: 3 },
                { title: '周四', value: 4 },
                { title: '周五', value: 5 },
                { title: '周六', value: 6 },
                { title: '周日', value: 7 }
            ]);
        } else if (type === 3) {
            const newList = Array.from({ length: 31 }, (v, k) => ({ title: `${k + 1}日`, value: k + 1 }));
            setWorkdays(newList);
        } else {
            setWorkdays([]);
        }
    };
    // 周期联动
    useEffect(() => {
        setCycleTaskCanPass(true);
        refreshWorkDays(form.getFieldValue('cycleTaskType'), false);
    }, [JSON.stringify(form.getFieldValue('cycleTaskType'))]);
    // 周期任务日期联动
    useEffect(() => {
        setCycleTaskCanPass(true);
    }, [JSON.stringify(form.getFieldValue('cycleTaskDayList'))]);

    const relativeLinkData = ((initInfo && initInfo.relateLinkList) || []).map((item, index) => ({
        key: index + 1,
        link: item
    }));
    const linkRef = React.useRef();

    useEffect(() => {
        const tempItem = getLocalItem(getPath(query, 'key', ''));
        seInitInfo(tempItem ? tempItem.taskParam : {});
        setParentRec(tempItem ? tempItem.record : {});
        setEndDate((tempItem && tempItem.taskParam && tempItem.taskParam.planEndTime) || '');
        fetchEmployeeList();
        fetchFrontList();
        fetchRelateTask();
        setPriorityList([
            { value: '紧急', key: 1 },
            { value: '高', key: 2 },
            { value: '中', key: 3 },
            { value: '低', key: 4 }
        ]);
        if (getPath(initInfo, 'estimateWorkDuration')) {
            setWorkTime(TimeFormatForm(getPath(initInfo, 'estimateWorkDuration')));
        }
        // 关联链接
        // if (getPath(initInfo, 'relateLinkList')) {
        //     const nextKeys = [];

        //     // const nextValue = [];
        //     getPath(initInfo, 'relateLinkList').forEach(() => {
        //         nextKeys.concat((id += 1));
        //         // nextValue.concat(item);
        //         // form.setFieldsValue({
        //         // relateLinkList[${id += 1}]: nextValue
        //         // });
        //     });

        //     // const nextKeys = keys && keys.concat((id += 1));
        //     setUrlList(nextKeys);

        //     // setUrlList(newArr);
        // }

        // 附件
        if (getPath(initInfo, 'attachmentList')) {
            const filesList = [];
            const files = getPath(initInfo, 'attachmentList') || [];
            files.forEach(item => {
                const { originName, url, keyName } = item;
                const fileObj = {
                    uid: keyName,
                    keyName,
                    name: originName,
                    oldName: originName,
                    url
                };
                filesList.push(fileObj);
            });
            setFileList(filesList);
            if (filesList.length >= 5) {
                setDisabled(true);
            }
        }
        if (getPath(initInfo, 'cycleTaskType')) {
            refreshWorkDays(getPath(initInfo, 'cycleTaskType'), true);
        }
        return () => {
            localStorage.removeItem(getPath(query, 'key'));
        };
    }, [getPath(query, 'key', ''), user.companyId]);

    React.useEffect(() => {
        if (getPath(query, 'type', '') === 'change_task' && initInfo && initInfo.parentTaskId) {
            getParentTaskList();
        }
    }, [initInfo]);

    return (
        <PageHeaderWrapper>
            <Card
                bordered={false}
                extra={extraButtons}
                title={getTitle(getPath(query, 'type'))}
                className={styles.cardFixed}
            >
                <Form {...formLayout} style={{ width: '90%' }}>
                    <FormContainer gutter={24} style={{ marginBottom: '32px' }}>
                        {getPath(query, 'type') === 'change_task' && form.getFieldValue('auditEmployeeCode') && (
                            <Form.Item label="温馨提示" vvspan={24} labelCol={{ md: 3 }} wrapperCol={{ md: 21 }}>
                                <span>变更执行人、截止时间、验收人字段需审核，其余无需审核；</span>
                            </Form.Item>
                        )}
                        {getPath(query, 'type') === 'restart_task' && parentRec && parentRec.launchAuditFlag && (
                            <Form.Item
                                label="温馨提示"
                                vvspan={24}
                                labelCol={{ md: 3 }}
                                wrapperCol={{ md: 21 }}
                                style={{ color: '#f5222d', marginBottom: 12 }}
                                className={styles.formLabel}
                            >
                                <span>当前任务审核不通过，请确认内容并重新提交</span>
                            </Form.Item>
                        )}
                        {getPath(query, 'type') === 'new_child_task' && getPath(parentRec, 'taskName', '') ? (
                            <Form.Item label="上一级任务" vvspan={24} labelCol={{ md: 3 }} wrapperCol={{ md: 21 }}>
                                <span
                                    style={{ color: '#ffa808', cursor: 'pointer', wordBreak: 'break-word' }}
                                    onClick={() => {
                                        history.push({
                                            pathname: '/work/task/taskdetail',
                                            query: {
                                                id: getPath(parentRec, 'id', ''),
                                                activeKey: 'detailMsg'
                                            },
                                            state: { tabRoute: true, tabRefresh: true }
                                        });
                                    }}
                                >
                                    {getPath(parentRec, 'taskName', '')}
                                </span>
                            </Form.Item>
                        ) : null}
                        {(!getPath(query, 'type') || (initInfo && !initInfo.parentTaskId)) && (
                            <Form.Item label=" " colon={false} style={{ marginBottom: 0 }}>
                                {getFieldDecorator('enableChildrenQueryFlag', {
                                    initialValue: getPath(initInfo, 'enableChildrenQueryFlag', false) || false,
                                    valuePropName: 'checked'
                                })(<Checkbox>当前一级任务允许被下级所有子任务查阅</Checkbox>)}
                            </Form.Item>
                        )}
                        {getPath(query, 'type') === 'change_task' && initInfo && initInfo.parentTaskId && (
                            <Form.Item label="上一级任务" vvspan={24} labelCol={{ md: 3 }} wrapperCol={{ md: 21 }}>
                                {getFieldDecorator('parentTaskId', {
                                    rules: [
                                        {
                                            required: true,
                                            message: '请选择上一级任务'
                                        }
                                    ],
                                    initialValue: getPath(initInfo, 'parentTaskId', undefined)
                                })(
                                    <Select
                                        placeholder="请选择上一级任务"
                                        allowClear
                                        showSearch
                                        dropdownClassName={styles.fixedSelect}
                                        dropdownStyle={{ maxHeight: 250, overflow: 'auto' }}
                                        getPopupContainer={trigger => trigger.parentNode}
                                        onSearch={handleSearchParent}
                                        onChange={handleChangeParent}
                                        filterOption={false}
                                        optionLabelProp="label"
                                    >
                                        {parentTaskList.map(item => (
                                            <Option key={item.taskId} value={item.taskId} label={item.taskName}>
                                                <TaskListItem data={item} />
                                            </Option>
                                        ))}
                                        {parentTaskList && parentTaskList.length > 0 && (
                                            <Option key="tips" value={undefined} label="" disabled>
                                                更多数据请输入关键字模糊搜索
                                            </Option>
                                        )}
                                    </Select>
                                )}
                            </Form.Item>
                        )}
                        <Form.Item label="任务名称" vvspan={24} labelCol={{ md: 3 }} wrapperCol={{ md: 21 }}>
                            {getFieldDecorator('taskName', {
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入任务名称'
                                    },
                                    {
                                        min: 1,
                                        max: 200,
                                        message: '不超过200个字!'
                                    },
                                    { whitespace: true, message: '请输入任务名称' }
                                ],
                                initialValue: getPath(initInfo, 'taskName', '')
                            })(<Input placeholder="请输入任务名称" allowClear></Input>)}
                        </Form.Item>
                        <Form.Item label="执行人">
                            {getFieldDecorator('executeEmployeeCode', {
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入执行人名称'
                                    },
                                    {
                                        validator(_, value, callback) {
                                            const auditId = form.getFieldValue('auditEmployeeCode');
                                            const acceptId = form.getFieldValue('acceptanceEmployeeCode');
                                            if (value && auditId && value === auditId) {
                                                return callback('不可与审核人重复');
                                            }
                                            if (value && acceptId && value === acceptId) {
                                                return callback('不可与验收人重复');
                                            }
                                            return callback();
                                        }
                                    }
                                ],
                                initialValue: getPath(initInfo, 'executeEmployeeCode', user.employeeCode)
                            })(
                                <TreeSelect
                                    showSearch
                                    allowClear
                                    dropdownClassName={styles.fixedSelect}
                                    dropdownStyle={{ maxHeight: 250, overflow: 'auto' }}
                                    getPopupContainer={trigger => trigger.parentNode}
                                    treeDefaultExpandAll
                                    treeNodeFilterProp="title"
                                    treeData={employeeList}
                                    suffixIcon={<Icon type="user" />}
                                    placeholder="请选择执行人"
                                    disabled={
                                        getPath(query, 'type') === 'change_task' &&
                                        getPath(initInfo, 'taskStatus', '') !== TaskStatus.READY
                                    }
                                ></TreeSelect>
                            )}
                        </Form.Item>
                        <Form.Item label="优先级">
                            {getFieldDecorator('taskPriority', {
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择'
                                    }
                                ],
                                initialValue: getPath(initInfo, 'taskPriority', undefined) || undefined
                            })(
                                <Select placeholder="请选择">
                                    {priorityList.map(item => (
                                        <Option key={item.key} value={item.key}>
                                            {item.value}
                                        </Option>
                                    ))}
                                </Select>
                            )}
                        </Form.Item>
                        <Form.Item label="开始时间">
                            {getFieldDecorator('planStartTime', {
                                rules: [
                                    {
                                        validator(_, value, callback) {
                                            if (value && form.getFieldValue('planEndTime')) {
                                                const endTime = form
                                                    .getFieldValue('planEndTime')
                                                    .format(
                                                        endMode === 'date'
                                                            ? 'YYYY-MM-DD 23:59:59'
                                                            : 'YYYY-MM-DD HH:mm:ss'
                                                    );
                                                const newValue = value.format(
                                                    startMode === 'date' ? 'YYYY-MM-DD 00:00:00' : 'YYYY-MM-DD HH:mm:ss'
                                                );
                                                if (endTime && moment(newValue) > moment(endTime)) {
                                                    return callback('不可大于截止时间');
                                                }
                                                return callback();
                                            }
                                            return callback();
                                        }
                                    }
                                ],
                                initialValue: getPath(initInfo, 'planStartTime')
                                    ? moment(getPath(initInfo, 'planStartTime'))
                                    : null
                            })(
                                <DatePicker
                                    style={{ width: '100%' }}
                                    showTime
                                    placeholder="请输入开始时间"
                                    format={startMode === 'date' ? 'MM-DD' : 'MM-DD HH:mm'}
                                    onOk={e => handleTime(e, 'start')}
                                    onChange={(e1, e2) => handleTimeChange(e1, e2, 'start')}
                                    onPanelChange={(e1, e2) => handleTimePanel(e1, e2, 'start')}
                                    disabled={
                                        getPath(query, 'type') === 'change_task' &&
                                        getPath(initInfo, 'taskStatus', '') !== TaskStatus.READY
                                    }
                                />
                            )}
                        </Form.Item>
                        <Form.Item label="截止时间">
                            {getFieldDecorator('planEndTime', {
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入截止时间'
                                    },
                                    {
                                        validator(_, value, callback) {
                                            if (value && form.getFieldValue('planStartTime')) {
                                                const startTime = form
                                                    .getFieldValue('planStartTime')
                                                    .format(
                                                        startMode === 'date'
                                                            ? 'YYYY-MM-DD 00:00:00'
                                                            : 'YYYY-MM-DD HH:mm:ss'
                                                    );
                                                const newValue = value.format(
                                                    endMode === 'date' ? 'YYYY-MM-DD 23:59:59' : 'YYYY-MM-DD HH:mm:ss'
                                                );
                                                if (startTime && moment(newValue) < moment(startTime)) {
                                                    return callback('不可小于开始时间');
                                                }
                                                return callback();
                                            }
                                            // if (value && initInfo && initInfo.parentPlanEndTime) {
                                            //     const newValue = value.format(
                                            //         endMode === 'date' ? 'YYYY-MM-DD 23:59:59' : 'YYYY-MM-DD HH:mm:ss'
                                            //     );
                                            //     if (moment(newValue).isAfter(initInfo.parentPlanEndTime)) {
                                            //         const str = moment(initInfo.parentPlanEndTime).format(
                                            //             initInfo.parentPlanEndTime.indexOf('23:59:59') !== -1
                                            //                 ? 'YYYY-MM-DD'
                                            //                 : 'YYYY-MM-DD HH:mm'
                                            //         );
                                            //         return callback(`不可大于上级任务截止时间${str}`);
                                            //     }
                                            // }
                                            return callback();
                                        }
                                    }
                                ],
                                initialValue: getPath(initInfo, 'planEndTime')
                                    ? moment(getPath(initInfo, 'planEndTime'))
                                    : null
                            })(
                                <DatePicker
                                    style={{ width: '100%' }}
                                    showTime
                                    placeholder="请输入截止时间"
                                    format={endMode === 'date' ? 'MM-DD' : 'MM-DD HH:mm'}
                                    onOk={e => handleTime(e, 'end')}
                                    onChange={(e1, e2) => handleTimeChange(e1, e2, 'end')}
                                    onPanelChange={(e1, e2) => handleTimePanel(e1, e2, 'end')}
                                />
                            )}
                        </Form.Item>
                        <Form.Item
                            label="是否周期任务"
                            style={{ marginBottom: 0 }}
                            validateStatus={cycleTaskCanPass ? '' : 'error'}
                            help={cycleTaskCanPass ? '' : '当前开始及截止时间无法创建周期任务'}
                        >
                            <div style={{ display: 'flex' }}>
                                <Form.Item
                                    style={
                                        showDays ? { width: 56, marginBottom: 0 } : { width: '100%', marginBottom: 0 }
                                    }
                                >
                                    {getFieldDecorator('cycleTaskFlag', {
                                        initialValue: getPath(initInfo, 'cycleTaskFlag', 0)
                                    })(
                                        <Select
                                            placeholder="请选择是否周期任务"
                                            disabled={
                                                getPath(query, 'type') === 'change_task' ||
                                                getPath(query, 'type') === 'restart_task'
                                            }
                                        >
                                            {[
                                                { value: '是', key: 1 },
                                                { value: '否', key: 0 }
                                            ].map(item => (
                                                <Option key={item.key} value={item.key}>
                                                    {item.value}
                                                </Option>
                                            ))}
                                        </Select>
                                    )}
                                </Form.Item>
                                {showDays && cycleTaskTypeForm}
                                {showDays && cycleTaskDayList}
                            </div>
                        </Form.Item>
                        <Form.Item label="通知方式">
                            {/* <Checkbox.Group
                                disabled
                                options={['IM消息', '系统消息']}
                                defaultValue={['IM消息', '系统消息']}
                            /> */}
                            {getFieldDecorator('noticeWayList', {
                                initialValue: getPath(initInfo, 'noticeWayList', [])
                            })(
                                <Checkbox.Group
                                    options={[
                                        // { label: 'IM消息', value: 1 },
                                        { label: '系统消息', value: 2 },
                                        { label: '邮箱', value: 3 }
                                        // { label: '短信', value: 4 }
                                    ]}
                                />
                            )}
                        </Form.Item>
                        {!showDays && (
                            <Form.Item label="审核人">
                                {getFieldDecorator('auditEmployeeCode', {
                                    rules: [
                                        {
                                            validator(_, value, callback) {
                                                const executeId = form.getFieldValue('executeEmployeeCode');
                                                if (value === user.employeeCode) {
                                                    return callback('不可选自己');
                                                }
                                                if (value && executeId && value === executeId) {
                                                    return callback('不可与执行人重复');
                                                }
                                                return callback();
                                            }
                                        }
                                    ],
                                    initialValue: getPath(initInfo, 'auditEmployeeCode') || undefined
                                })(
                                    <TreeSelect
                                        showSearch
                                        allowClear
                                        dropdownClassName={styles.fixedSelect}
                                        dropdownStyle={{ maxHeight: 250, overflow: 'auto' }}
                                        getPopupContainer={trigger => trigger.parentNode}
                                        treeDefaultExpandAll
                                        treeNodeFilterProp="title"
                                        treeData={employeeList}
                                        suffixIcon={
                                            <i className="icon iconfont iconshenheren1" style={{ fontSize: '12px' }} />
                                        }
                                        disabled={
                                            getPath(query, 'type') === 'change_task' &&
                                            getPath(initInfo, 'auditStatus') === 3
                                        }
                                        placeholder="请选择审核人"
                                    ></TreeSelect>
                                )}
                            </Form.Item>
                        )}
                        {!showDays && (
                            <Form.Item label="验收人">
                                {getFieldDecorator('acceptanceEmployeeCode', {
                                    rules: [
                                        {
                                            validator(_, value, callback) {
                                                const executeId = form.getFieldValue('executeEmployeeCode');
                                                if (value && executeId && value === executeId) {
                                                    return callback('不可与执行人重复');
                                                }
                                                return callback();
                                            }
                                        }
                                    ],
                                    initialValue: getPath(initInfo, 'acceptanceEmployeeCode') || undefined
                                })(
                                    <TreeSelect
                                        showSearch
                                        allowClear
                                        dropdownClassName={styles.fixedSelect}
                                        dropdownStyle={{ maxHeight: 250, overflow: 'auto' }}
                                        getPopupContainer={trigger => trigger.parentNode}
                                        treeDefaultExpandAll
                                        treeNodeFilterProp="title"
                                        treeData={employeeList}
                                        placeholder="请选择验收人"
                                        suffixIcon={
                                            <i className="icon iconfont iconyanshouren1" style={{ fontSize: '12px' }} />
                                        }
                                        disabled={
                                            getPath(query, 'type') === 'change_task' &&
                                            getPath(initInfo, 'acceptanceStatus') === 3
                                        }
                                    ></TreeSelect>
                                )}
                            </Form.Item>
                        )}
                        {!showDays && (
                            <Form.Item label="参与人" vvspan={24} labelCol={{ md: 3 }} wrapperCol={{ md: 21 }}>
                                {getFieldDecorator('participantEmployeeCodeList', {
                                    initialValue: getPath(initInfo, 'participantEmployeeCodeList') || undefined
                                })(
                                    <TreeSelect
                                        multiple
                                        showArrow
                                        allowClear
                                        showSearch
                                        maxTagCount={10}
                                        suffixIcon={<Icon type="user" />}
                                        placeholder="请选择参与人"
                                        dropdownClassName={styles.fixedSelect}
                                        dropdownStyle={{ maxHeight: 250, overflow: 'auto' }}
                                        getPopupContainer={trigger => trigger.parentNode}
                                        treeDefaultExpandAll
                                        treeNodeFilterProp="title"
                                        treeData={employeeList}
                                    ></TreeSelect>
                                )}
                            </Form.Item>
                        )}
                        <Form.Item label="预估工时">
                            {getFieldDecorator('estimateWorkDuration', {
                                initialValue: getPath(initInfo, 'estimateWorkDuration') / 60 || null
                            })(
                                <InputNumber
                                    min={0}
                                    max={9999.9}
                                    placeholder="请输入"
                                    precision={1}
                                    formatter={value => `${value}`.replace('.0', '')}
                                    style={{ width: 140 }}
                                />
                            )}
                            &nbsp;&nbsp;&nbsp;&nbsp;{workTime}
                        </Form.Item>
                        <Form.Item label="通用类型">
                            {getFieldDecorator('generalType', {
                                initialValue: getPath(initInfo, 'generalType', undefined)
                            })(
                                <Select placeholder="请选择通用类型" style={{ width: '100%' }} allowClear>
                                    {[
                                        { value: '会议', key: 1 },
                                        { value: '培训', key: 2 },
                                        { value: '团建', key: 3 },
                                        { value: '学习', key: 4 },
                                        { value: '其他', key: 99 }
                                    ].map(item => (
                                        <Option key={item.key} value={item.key}>
                                            {item.value}
                                        </Option>
                                    ))}
                                </Select>
                            )}
                        </Form.Item>
                        <Form.Item label="提前提醒">
                            <div style={{ display: 'flex', paddingTop: 4 }}>
                                {getFieldDecorator('remindType', {
                                    initialValue: getPath(initInfo, 'remindType', 0)
                                })(
                                    <Select
                                        placeholder="请选择提醒方式"
                                        disabled={getPath(query, 'type') === 'change_task'}
                                    >
                                        {[
                                            { value: '不提醒', key: 0 },
                                            { value: '固定时间', key: 1 }
                                            // { value: '指定时间', key: 2 }
                                        ].map(item => (
                                            <Option key={item.key} value={item.key}>
                                                {item.value}
                                            </Option>
                                        ))}
                                    </Select>
                                )}
                                {advanceAlert === 1 && getRemindDuration()}
                                {advanceAlert === 1 && getRemindDurationUnit()}
                                {advanceAlert === 2 && getRemindDate()}
                            </div>
                        </Form.Item>
                        {!showDays && (
                            <Form.Item label="是否个人隐私">
                                {getFieldDecorator('personalPrivacyFlag', {
                                    initialValue: getPath(initInfo, 'personalPrivacyFlag', 0)
                                })(
                                    <Select
                                        placeholder="请选择是否个人隐私"
                                        disabled={
                                            getPath(query, 'type') === 'change_task' ||
                                            getPath(query, 'type') === 'restart_task' ||
                                            getPath(query, 'type') === 'new_child_task'
                                        }
                                    >
                                        {[
                                            { value: '是（仅个人可见，不计工时）', key: 1 },
                                            { value: '否', key: 0 }
                                        ].map(item => (
                                            <Option key={item.key} value={item.key}>
                                                {item.value}
                                            </Option>
                                        ))}
                                    </Select>
                                )}
                            </Form.Item>
                        )}
                        {/* 第一阶段不做 */}
                        {/* <Form.Item label="关联产品" vvspan={24} labelCol={{ md: 3 }} wrapperCol={{ md: 21 }}>
                            {getFieldDecorator(
                                'relationProduct',
                                {}
                            )(
                                <Select placeholder="请选择关联产品">
                                    {noticeWayList.map(item => (
                                        <Option key={item.key} value={item.value}>
                                            {item.value}
                                        </Option>
                                    ))}
                                </Select>
                            )}
                        </Form.Item>
                        <Form.Item label="关联项目" vvspan={24} labelCol={{ md: 3 }} wrapperCol={{ md: 21 }}>
                            {getFieldDecorator(
                                'relationApp',
                                {}
                            )(
                                <Select placeholder="请选择关联项目">
                                    {noticeWayList.map(item => (
                                        <Option key={item.key} value={item.value}>
                                            {item.value}
                                        </Option>
                                    ))}
                                </Select>
                            )}
                        </Form.Item>
                        <Form.Item label="关联计划" vvspan={24} labelCol={{ md: 3 }} wrapperCol={{ md: 21 }}>
                            {getFieldDecorator(
                                'relationPlan',
                                {}
                            )(
                                <Select placeholder="请选择关联计划">
                                    {noticeWayList.map(item => (
                                        <Option key={item.key} value={item.value}>
                                            {item.value}
                                        </Option>
                                    ))}
                                </Select>
                            )}
                        </Form.Item> */}
                        {/* 第一阶段不做 */}
                        <Form.Item label="前置任务" vvspan={24} labelCol={{ md: 3 }} wrapperCol={{ md: 21 }}>
                            {getFieldDecorator('frontTaskId', {
                                initialValue: getPath(initInfo, 'frontTaskId', undefined)
                            })(
                                <Select
                                    placeholder="请选择前置任务"
                                    allowClear
                                    showSearch
                                    dropdownClassName={styles.fixedSelect}
                                    dropdownStyle={{ maxHeight: 250, overflow: 'auto' }}
                                    getPopupContainer={trigger => trigger.parentNode}
                                    onSearch={handleSearchFront}
                                    onChange={handleChangeFront}
                                    filterOption={false}
                                    optionLabelProp="label"
                                >
                                    {frontList.map(item => (
                                        <Option key={item.taskId} value={item.taskId} label={item.taskName}>
                                            <TaskListItem data={item} />
                                        </Option>
                                    ))}
                                    {frontList && frontList.length > 0 && (
                                        <Option key="tips" value={undefined} label="" disabled>
                                            更多数据请输入关键字模糊搜索
                                        </Option>
                                    )}
                                </Select>
                            )}
                        </Form.Item>
                        <Form.Item label="关联任务" vvspan={24} labelCol={{ md: 3 }} wrapperCol={{ md: 21 }}>
                            {getFieldDecorator('relateTaskId', {
                                initialValue: getPath(initInfo, 'relateTaskId', undefined)
                            })(
                                <Select
                                    placeholder="请选择关联任务"
                                    allowClear
                                    showSearch
                                    dropdownClassName={styles.fixedSelect}
                                    dropdownStyle={{ maxHeight: 250, overflow: 'auto' }}
                                    getPopupContainer={trigger => trigger.parentNode}
                                    onSearch={handleSearch}
                                    onChange={handleChangeRelate}
                                    filterOption={false}
                                    optionLabelProp="label"
                                >
                                    {relateTask.map(item => (
                                        <Option key={item.taskId} value={item.taskId} label={item.taskName}>
                                            <TaskListItem data={item} />
                                        </Option>
                                    ))}
                                    {relateTask && relateTask.length > 0 && (
                                        <Option key="tips" value={undefined} label="" disabled>
                                            更多数据请输入关键字模糊搜索
                                        </Option>
                                    )}
                                </Select>
                            )}
                        </Form.Item>
                        <Form.Item
                            label="关联链接"
                            vvspan={24}
                            labelCol={{ md: 3 }}
                            wrapperCol={{ md: 21 }}
                            style={{ marginBottom: '0' }}
                        >
                            {getFieldDecorator('relateLinkList', {
                                validateTrigger: ['onChange', 'onBlur'],
                                rules: [
                                    {
                                        validator(_, value, callback) {
                                            value.some(item => {
                                                const errorMessage = linkRef.current.getValidateError(item.link);
                                                if (errorMessage) {
                                                    callback(errorMessage);
                                                    return true;
                                                }
                                                return false;
                                            });
                                            callback();
                                        }
                                    }
                                ],
                                initialValue: relativeLinkData
                            })(<RelativeLink ref={linkRef} />)}
                        </Form.Item>
                        <Form.Item label="关联附件" vvspan={24} labelCol={{ md: 3 }} wrapperCol={{ md: 21 }}>
                            {getFieldDecorator('resourceRelation', {
                                // initialValue: {
                                //     allFileList: fileList || [],
                                //     uploadResourceFile: null
                                // }
                            })(
                                <FileUpload
                                    // onChange={handleFileUpload}
                                    setFileList={handleFileUpload}
                                    checkFileSizeMsg="文件大小不能超过50MB！"
                                    checkFileSize={50}
                                    fileList={fileList}
                                    uploadResource={uploadResource}
                                    categoryCode="attachmentList"
                                    // checkFileType="TXT,DOC,DOCX,XLS,XLSX,PPT,PPTX,PDF,EDC,SSP,DWG,EDCS,
                                    // BMP,JPG,PNG,TIF,GIF,PCX,TGA,EXIF,FPX,SVG,PSD,CDR,PCD,DXF,UFO,
                                    // EPS,AI,RAW,WMF,WEBP"
                                    checkFileType="TXT,DOC,DOCX,XLS,XLSX,PPT,PPTX,PDF,EDC,SSP,DWG,EDCS,
                                    BMP,JPG,PNG,TIF,GIF,PCX,TGA,EXIF,FPX,SVG,PSD,CDR,PCD,DXF,UFO,EPS,AI,
                                    RAW,WMF,WEBP,Xmind,ZIP,rar,zip,CAB,ARJ,LZH,TAR,GZ,ACE,UUE,BZ2,JAR,ISO,rp"
                                    checkFileTypeMsg="附件格式不合规，请确认！"
                                >
                                    <Button type="link" disabled={disabled} style={{ padding: '0' }}>
                                        添加附件
                                    </Button>
                                </FileUpload>
                            )}
                        </Form.Item>
                        {/* <Form.Item label="抄送给" vvspan={24} labelCol={{ md: 3 }} wrapperCol={{ md: 21 }}>
                            {getFieldDecorator('give')(
                                <Select mode="multiple" placeholder="请选择" allowClear>
                                    {employeeList.map(item => (
                                        <Option key={item.key} value={item.key}>
                                            {item.title}
                                        </Option>
                                    ))}
                                </Select>
                            )}
                        </Form.Item> */}
                        <Form.Item label="描述" vvspan={24} labelCol={{ md: 3 }} wrapperCol={{ md: 21 }}>
                            {getFieldDecorator('taskDesc', {
                                initialValue: getPath(initInfo, 'taskDesc')
                                    ? BraftEditor.createEditorState(`${getPath(initInfo, 'taskDesc')}`)
                                    : BraftEditor.createEditorState(null)
                            })(
                                <BraftEditor
                                    media={{
                                        uploadFn: myUploadFn,
                                        validateFn: myValidateFn,
                                        accepts: {
                                            image: 'image/png,image/jpeg,image/gif'
                                        }
                                    }}
                                    onChange={handleEditorChange}
                                    placeholder="请输入任务描述"
                                    controls={controls}
                                    excludeControls={['fullscreen']}
                                    imageControls={[
                                        {
                                            onClick: block => {
                                                console.log(block);
                                            } // 指定控件点击后的回调，参数为当前图片的block对象
                                        },
                                        'align-left',
                                        'align-center',
                                        'align-right',
                                        'size',
                                        'remove'
                                    ]}
                                    style={{
                                        border: '1px solid #d9d9d9',
                                        borderTopWidth: '1.02px',
                                        borderRadius: '4px',
                                        marginTop: '4px'
                                    }}
                                />
                            )}
                        </Form.Item>
                        {showChildList()}
                    </FormContainer>
                </Form>
            </Card>
        </PageHeaderWrapper>
    );
};

export default Form.create()(AddTask);
